package com.mxin.ui.test

import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mxin.ui.R
import com.mxin.ui.base.BaseActivity
import com.mxin.ui.list.*
import com.scwang.smart.refresh.layout.api.RefreshLayout


class TestRefreshListActivity : BaseActivity(), IRefreshListener {

    private val listViewHelper = BaseListViewHelper<Aty>()
    private lateinit var recyclerView: RecyclerView
    private lateinit var refreshLayout:RefreshLayout

    override fun setContentView() {
        setContentView(R.layout.ui_activity_test_aty)
    }

    override fun showLoadingView(): View? = refreshLayout as View

    override fun initView() {
        val titleStub = findViewById<ViewStub>(R.id.titleView)
        setTitleView(titleStub, "分页List列表")
        val contentView = findViewById<ViewGroup>(R.id.layout_content)
        recyclerView = listViewHelper.bindListView(contentView){
            it.layoutManager = LinearLayoutManager(this)
            it.adapter = AtyAdapter(mutableListOf())
        }
        refreshLayout = listViewHelper.bindRefreshLayout(recyclerView, this){
            it.setEnableRefresh(true)
            it.setEnableLoadMore(true)
        }
        listViewHelper.subscribeData {
            when{
                it.state==PageDataState.Null ->{
                    showLoadFailed()
                }
                else ->{
                    showLoadSuccess()
                }
            }
        }
    }

    override fun initData() {
        showLoading()
        onLoadRetry()
    }

    override fun onLoadRetry() {
        //延迟3秒加载
        recyclerView.postDelayed({
            listViewHelper.emit(getListData(Page()))
        }, 3000)

    }

    private fun getListData(page: Page):PageData<Aty>{
        val data = mutableListOf<Aty>()
        val positionStart = page.page*page.pageSize
        repeat(page.pageSize){
            data.add(Aty("描述花语：${positionStart+it}", TestRefreshListActivity::class.java))
        }
        return data.toPageData(page)
    }

    override fun refresh(page: Page) {
        listViewHelper.emit(getListData(page))

    }

    override fun loadMore(page: Page) {
        listViewHelper.emit(getListData(page))
    }


}
